package belf.migrate.engine.job.structure.helper;

import belf.migrate.api.exception.CatalogException;
import belf.migrate.api.table.schema.Catalog;
import belf.migrate.api.table.schema.TablePath;
import belf.migrate.api.taskconf.JobContext;
import belf.migrate.api.type.DbObjectType;
import belf.migrate.api.type.LogLevelType;
import belf.migrate.api.util.PostLog;
import belf.migrate.api.job.Job;
import belf.migrate.engine.job.JobResult;
import belf.migrate.engine.job.JobResultItem;
import belf.migrate.api.taskconf.Task;
import belf.migrate.api.util.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.List;

import static belf.migrate.api.job.JobCode.*;

@Slf4j
public class DropViewTool extends NonTableTool {

    public DropViewTool(Job job) {
        super(job);
    }

    public DropViewTool(Job job, JobContext jobContext) {
        super(job, jobContext);
    }

    @Override
    public JobResult run() {
        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "删除视图开始！",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        JobResult jobResult = new JobResult(SUCCESS, "删除选中的视图成功");
        Catalog sinkCatalog = jobContext.getSinkCatalog();

        try {
            List<String> viewNames; //待创建的视图名称列表
            // 若限定了要处理的视图名称
            if (job.getMissions() != null && !job.getMissions().isEmpty()) {
                viewNames = job.getMissions();
            } else {
                viewNames = sinkCatalog.listViewNames(jobContext.getValidSourceDatabase(), jobContext.getValidSinkDatabase());
            }

            if (null != viewNames) {
                for (String viewName : viewNames) {
                    jobContext.addProgress(DbObjectType.VIEW.getTypeName(), viewNames.size());
                    JobResultItem jobResultItem = process(viewName, sinkCatalog);
                    jobResult.addItem(jobResultItem);
                    if (jobResultItem.getCode() != SUCCESS
                            && job.getTask().getTaskPolicy() == Task.TaskPolicy.ERROR_STOP) {
                        break;  //创建表遇到错误即返回
                    }
                }
            }
        } catch (CatalogException e) {
            e.printStackTrace();
        }
        if (jobResult.getFailtures() > 0) {
            jobResult.setCode(DROP_VIEW_ERROR);
            jobResult.setMessage("删除选中的视图失败");
            log.error("Drop Some Views Of {} Failed.", jobContext.getValidSinkDatabase());
        } else {
            log.info("Drop All Views Of {} Successfully.", jobContext.getValidSinkDatabase());
        }

        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "删除视图结束！",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        return jobResult;
    }

    private JobResultItem process(String viewName, Catalog sinkCatalog) {
        String startTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        TablePath viewPath = TablePath.of(jobContext.getTaskConf().getSinkConf().getDatabaseName(),
                jobContext.getTaskConf().getSinkConf().getSchemaName(),
                viewName,
                getSinkQualifiersModel());
        try {
            boolean result = sinkCatalog.dropView(viewPath);
            if (!result) {
                PostLog.sendLogModel(
                        job.getJobId(),
                        job.getTask().getTaskType().getName(),
                        "目标库" + "删除视图失败：" + viewName,
                        LogLevelType.ERROR.getType(),
                        EXECUTING,
                        jobContext.getProgress());
                return new JobResultItem(viewName,
                        viewPath.getCaseTableName(),
                        DROP_VIEW_ERROR,
                        "目标库" + "删除视图失败：" + viewName,
                        "",
                        DbObjectType.VIEW.getTypeName(),
                        startTime,
                        DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"),
                        null,
                        sinkCatalog.getDropViewSql(viewPath));
            }
//            sinkCatalog.
        } catch (CatalogException e) {
            e.printStackTrace();
            PostLog.sendLogModel(
                    job.getJobId(),
                    job.getTask().getTaskType().getName(),
                    "目标库" + "删除视图失败：" + viewName,
                    LogLevelType.ERROR.getType(),
                    EXECUTING,
                    jobContext.getProgress());
            return new JobResultItem(viewName,
                    viewPath.getCaseTableName(),
                    DROP_VIEW_ERROR,
                    "目标库" + "删除视图失败：" + viewName,
                    ExceptionUtils.toString(e),
                    DbObjectType.VIEW.getTypeName(),
                    startTime,
                    DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"),
                    null,
                    sinkCatalog.getDropViewSql(viewPath));
        }

        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "删除视图" + viewName + "成功",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        JobResultItem jobResultItem = new JobResultItem(
                viewName,
                viewPath.getCaseTableName(),
                SUCCESS,
                "删除视图" + viewName + "成功");
        jobResultItem.setSinkDdl(sinkCatalog.getDropViewSql(viewPath));
        jobResultItem.setStartTime(startTime);
        jobResultItem.setEndTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        jobResultItem.setType(DbObjectType.VIEW.getTypeName());
        return jobResultItem;
    }
}
